#!/usr/bin/env python3
import random

import requests
from datetime import datetime
import os.path
import time

import json

import config

from db_helper import DbHelper
from http_helper import HttpHelper
from param_model import ParamModel

http = HttpHelper()
db = DbHelper()
param = ParamModel()

creator_token = ''


def write_act_comments():
    resp = http.fetch_my_act()
    for record in resp['records']:
        # print('----', record['id'], record['evaluateStatus'], record['clubId'])
        if record['clubId'] == 10727 and record['evaluateStatus'] == 0:
            comment = db.get_random_comment()
            print(f'新建评论 act:{act_id} and comment:{comment.content}')

            param = {
                "activityId": act_id,
                "clubId": None,
                "evaluateType": 1,
                "mainScore": 5,
                "serviceScore": 5,
                "environmentScore": 5,
                "experienceScore": 5,
                "content": comment.content,
                "pics": comment.image_url,
                "evaluateTarget": 0
            }
            http.create_comment(param)
            break


def assign_temp_admin():
    print('开始为丰台活动设置临时管理员')
    http.set_flash_token(creator_token)
    acts = http.fetch_club_activities(config.HY_CLUB_ID)['records']
    for act in acts:
        if act['activityAddress'] == '康城羽毛球馆' and (act['startTime'] == '12:00' or act['startTime'] == '14:00'):
            print('康城下午场活动：', act['id'])
            admins = http.fetch_temp_admin(act['id'])
            if not isinstance(admins, list):
                # 未设置管理员时此处不会返回列表
                ret = http.add_temp_admin(act_id=act['id'], member_id_list=[2990797])
                print('为活动设置临时管理员......', ret)
                # print('add admin result:::::::::', ret)
        elif act['activityAddress'] == '209玉泉营羽毛球馆' or (
                act['activityAddress'] == '康城羽毛球馆' and act['startTime'] == '18:00'):
            admins = http.fetch_temp_admin(act['id'])
            if not isinstance(admins, list):
                # 未设置管理员时此处不会返回列表
                ret = http.add_temp_admin(act_id=act['id'], member_id_list=[2771390, 2675656])
                print('为活动设置临时管理员......', ret)
        time.sleep(3)


def confirm_account():
    # 检查所有账号的token过期情况d
    accounts = db.get_user_accounts()
    for account in accounts:
        # print('user:', account.to_dict())
        data = account.to_dict()
        last_update = data['last_update']
        expired = False

        # print("时间差:", datetime.now().timestamp() - last_update.timestamp())
        if last_update is not None and datetime.now().timestamp() - last_update.timestamp() > config.TOKEN_EXP_SECONDS:
            expired = True

        access_token = data['access_token']
        if access_token is None or expired:
            print('token无效或已过期，重新获取', data['phone'], data['password'])
            access_token = 'xxxxxxxxxxxxxxx'
            # print('phone:', data['phone'], access_token)
            db.update_account_account(data['phone'], access_token)
            # 等待10秒再处理下一个账号
            # time.sleep(10)
        # player_tokens.append(access_token)
        # if data['member_name'] == '小伙伴':
        #     http.set_flash_token(access_token)
        #     ret = http.join_club(8474)
        #     print('join club result:::::::::', ret)


if __name__ == "__main__":

    confirm_account()

